import 'package:bxultimate/data/request/user_request.dart';
import 'package:bxultimate/domain/auth/login_user.dart';
import 'package:bxultimate/shared/constant/app_constant.dart';
import 'package:bxultimate/shared/shared.dart';
import 'package:get/get.dart';

import 'config_store.dart';

class AuthStore extends GetxController {
  static AuthStore get to => Get.find();

  // 是否登录
  final _isLogin = false.obs;

  // 令牌 token
  String token = '';

  // 用户 profile
  final _profile = LoginUser().obs;

  set profile(value) => _profile.value = value;

  bool get isLogin => _isLogin.value;

  LoginUser get profile => _profile.value;

  bool get hasToken => token.isNotEmpty;

  @override
  Future<void> onInit() async {
    super.onInit();
    token = UtilSp.getString(AppConstant.authorizationToken, defValue: '')!;
    if (token != '') {
      await getProfile();
    }
  }

  String getUserAvatar() {
    return AuthStore.to.profile.headImgUrl != null
        ? ConfigStore.to.baseFileUrl + AuthStore.to.profile.headImgUrl!
        : "https://minio.sxmbxt.com/static/img/newimg/nameimg.png";
  }

  // 保存 token
  Future<void> login(String value) async {
    await UtilSp.putString(AppConstant.authorizationToken, value);
    token = value;
    await getProfile();
  }

  // 获取 profile
  Future<void> getProfile() async {
    if (token.isEmpty) return;
    var result = await UserRequest.profile();
    profile = result;
    _isLogin.value = true;
  }

  // 注销
  Future<void> logout() async {
    // if (_isLogin.value) await UserAPI.logout();
    // await UserAPI.logout();
    await UtilSp.remove(AppConstant.authorizationToken);
    _profile(LoginUser());
    _isLogin.value = false;
    token = '';
  }
}
